﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

namespace CodeGame.LuaLibary
{
    class LuaCSharpBinding
    {
        private Type EntryPointClass;

        public LuaCSharpBinding(Assembly asm, string entryType)
        {
            this.EntryPointClass = asm.GetType(entryType, true);
        }

        public void Invoke(string args)
        {
            this.EntryPointClass.InvokeMember("Main", BindingFlags.InvokeMethod, null, null, new object[] { args });
        }
    }

    static class luaLib_csharp
    {

        private static CSharpCodeProvider Provider = new CSharpCodeProvider();

        [LuaHelp("Compiles a code from a string of csharp code")]
        public static LuaCSharpBinding compileCode(string code, string entry)
        {
            CompilerParameters prams = new CompilerParameters();
            prams.GenerateInMemory = true;
            prams.ReferencedAssemblies.Add(Environment.GetCommandLineArgs()[0]);
            CompilerResults res = luaLib_csharp.Provider.CompileAssemblyFromSource(prams, code);

            if (res.Errors.Count > 0)
            {
                Singletons.Console.Print("Compile Errors:", Singletons.ErrorText);
                foreach (CompilerError item in res.Errors)
                {
                    Singletons.Console.Print(item.Line.ToString() + " : " + item.ErrorNumber + " : " + item.ErrorText, Singletons.ErrorText);
                }
                return null;
            }
            else
            {
                return new LuaCSharpBinding(res.CompiledAssembly, entry);
            }
        }

        [LuaHelp("Invokes a csharp function")]
        public static void invokeFunction(LuaCSharpBinding binding, string args)
        {
            binding.Invoke(args);
        }

    }
}
